// packageK/popularize-home/popularize-home.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    active: 0,
    isAgent: 0,
    levels: [],
    statistics: {},
    address: null,
    isLock: false
  },

  /**
   * 会员升级/佣金玩法切换
   * @param {Object} e 
   */
  tabChange: function(e) {
    const { index } = e.currentTarget.dataset
    this.setData({ active: index })
  },

  /**
   * 获取页面数据
   */
  getPageData: function() {
    const urlStr = app.getNetAddresss('plugin.commission.api.index.index')
    const _this = this
    wx.showLoading({ title: '数据加载中...' })
    app._getNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const { is_agent, levels, member_address } = resData.data
          // 分销商获取【我的收益VIP】数据
          _this.getWithdrawalStatistic()
          _this.setData({
            isAgent: is_agent,
            levels,
            address: member_address
          })
        } else {
          app.tips(resData.msg || '数据获取失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 获取提现统计数据
   */
  getWithdrawalStatistic: function() {
    const urlStr = app.getNetAddresss('plugin.commission.api.commission.statistic')
    const _this = this
    wx.showLoading({ title: '数据加载中...' })
    app._getNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          _this.setData({ statistics: resData.data})
        } else {
          app.tips(resData.msg || '统计数据获取失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 提现
   */
  income: async function() {
    const tmplIds = await this.getTmplIds(3)
    const _this = this
    this.wxSubscriptionMessage(tmplIds, () => {
      _this.gotoIncome()
    })
  },

  /**
   * 获取提现订阅消息tmplIds
   * @param {String | Number} small_type 订阅消息参数
   * @returns {Promise}
   */
  getTmplIds: function(small_type = '') {
    const _this = this
    return new Promise((resolve, reject) => {
      const { isLock } = this.data
      if (isLock) {
        app.tips('操作过于频繁！')
        return
      }
      _this.setData({ isLock: true })
      const urlStr = app.getNetAddresss('member.member.getMiniTemplateCorrespond')
      wx.showLoading({ title: '正在获取tmplIds...'})
      app._getNetWork({
        url: urlStr,
        data: { small_type },
        success: function(res) {
          const resData = res.data
          if (resData.result == 1) {
            resolve(resData.data)
          } else {
            app.tips(resData.msg || '数据获取失败！')
          }
        },
        complete: function() {
          _this.setData({ isLock: false })
          wx.hideLoading()
        }
      })
    })
  },

  /**
   * 订阅提现消息(提现状态通知/提现成功通知)
   * @param {Array} ids 订阅消息的tmplIds
   * @param {Function} callBack 订阅后的处理方法
   */
  wxSubscriptionMessage: function(ids = [], callBack) {
    if (!ids.length) return
    const tmplIds = ids.map(item => {
      return item.template_id
    })
    wx.requestSubscribeMessage({
      tmplIds,
      complete: function() {
        callBack && callBack()
      }
    })
  },

  /**
   * 跳转到提现页面
   */
  gotoIncome: function() {
    wx.navigateTo({
      url: '/packageA/member/withdrawal/withdrawal',
    })
  },

  /**
   * 支付会员开通费
   * @param {Object} e 会员等级信息
   */
  payMemberFees: async function(e) {
    const tmplIds = await this.getTmplIds(1)
    const _this = this
    const level = e.detail
    this.wxSubscriptionMessage(tmplIds, () => {
      _this.createPayOrder(level)
    })
  },

  /**
   * 创建支付订单
   * @param {Object} level 会员等级
   */
  createPayOrder: function(level) {
    const { address } = this.data
    const { goods_id } = level
    const urlStr = app.getNetAddresss('order.create')
    const _this = this
    let json = {
      address: address ? encodeURIComponent(JSON.stringify(address)) : '',
      cart_ids: '[]',
      dispatch_type_id: 0,
      goods: JSON.stringify([
        {
          share_id: 0,
          goods_id: goods_id,
          total: 1,
          option_id: 0
        }
      ]),
      invoice: {},
      mark: 0,
      member_coupon_ids: '[]',
      no_deduction_ids: '1',
      orders: '[]',
      positioning_success: 1,
      register_city: address && address.city ? address.city : '',
      register_province: address && address.province ? address.province : ''
    }
    wx.showLoading({ title: '正在生成支付订单...'})
    app._postNetWork({
      url: urlStr,
      data: json,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          wx.redirectTo({
            url: '/packageD/buy/orderPay/orderPay?status=2&order_id=' + resData.data.order_ids,
          })
        } else {
          app.tips(resData.msg || '生成订单失败失败！')
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },



  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getPageData()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(options) {
    return {
      title: '分享赚钱，即得佣金',
      path: '/packageK/popularize-home/popularize-home',
      imageUrl: '/image/popularize/share-poster.png'
    }
  }
})